package net.lzzy.practices.utils;

import net.lzzy.practices.web.models.VmUser;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.*;

/**
 * @author zly on 2022/5/11
 * Description:
 */
@Component
public class AuthUtils {
    public  static  final List<VmUser>USERS = new ArrayList<>();
    public  static  int minutes;

    @Value("$(app.over.minutes)")
    public static void setMinutes(int minutes) {
        AuthUtils.minutes = minutes;
    }
    public  static  VmUser getUser(String token){
        return  USERS
                .stream()
                .filter( u -> u.getToken().equals(token))
                .findFirst()
                .orElse(null);
    }
    public  static  boolean invalid(UUID userId, String token){
        VmUser user = getUser(token);
        if(user == null || isOverTime(user)){
            return  true;
        }
        boolean valid = user.getId().equals(userId);
        if(valid){
            user.setLastLogin(new Date());
        }
        return ! valid;
    }

    private  static  boolean isOverTime(VmUser user){
        long offMillis = System.currentTimeMillis() - user.getLastLogin().getTime();
        long minutes = offMillis / (1000 * 60);
        boolean over = minutes > AuthUtils.minutes;
        if(over){
            USERS.remove(user);
        }
        return  over;
    }
    public  static  boolean illegalUser(String token , int[] allowedRoles){
        VmUser user = getUser(token);
        if(user == null || isOverTime(user)){
            return  true;
        }
        user.setLastLogin(new Date());
        return Arrays.stream(allowedRoles).noneMatch(r -> r == user.getType());
    }
    public  static  String logout(String token){
        VmUser user =getUser(token);
        if(user == null){
            return  "注销失败，未发现登录记录";
        }
        USERS.remove(user);
        return "注销成功";
    }
}

